package com.zmx.job.admin.core.thread;

import com.zmx.core.dto.RequestDataInfo;
import com.zmx.core.server.ClientInstanceInfo;
import com.zmx.core.utils.AESUtil;
import com.zmx.core.utils.JacksonUtil;
import com.zmx.job.admin.core.conf.MallAdminConfig;
import com.zmx.job.admin.core.dto.JobDistributeInfo;
import com.zmx.job.admin.enums.RoutStrategyEnum;
import com.zmx.job.admin.core.queue.JobQueue;
import com.zmx.job.admin.utils.RandomElementUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @Description: 任务队列分配调度
 * @ClassName: JobSendHelper
 * @Author zhaomxr
 * @Date 2021-12-20 16:54
 */
@Slf4j
public class JobQueueHelper {

    private static JobQueueHelper instance = new JobQueueHelper();

    public static JobQueueHelper getInstance() {
        return instance;
    }

    private static boolean sendStop = false;

    ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
            100,
            100,
            60L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(2000));

    public void start() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!sendStop) {
                    if (!JobQueue.empty()) {
                        //取出队头任务
                        JobDistributeInfo jobDistributeInfo = JobQueue.poll();
                        String name = jobDistributeInfo.getName();
                        RoutStrategyEnum strategyEnum = jobDistributeInfo.getRoutStrategyEnum();
                        if (StringUtils.isEmpty(name) || strategyEnum == null) {
                            log.error("任务参数错误！{}", jobDistributeInfo);
                            continue;
                        }

                        Map<String, Boolean> onLineInstance = ClientInstanceInfo.getOnLineInstance();
                        if (onLineInstance == null || onLineInstance.keySet() == null || onLineInstance.keySet().size() == 0) {
                            log.error("当前不存在在线客户端！");
                            continue;
                        }

                        poolExecutor.execute(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    MallAdminConfig mallAdminConfig = MallAdminConfig.getMallAdminConfig();

                                    RequestDataInfo requestDataInfo = new RequestDataInfo();
                                    requestDataInfo.setVerification(AESUtil.aesEncrypt(mallAdminConfig.getUsername() + mallAdminConfig.getPassword(), mallAdminConfig.getSecret()));
                                    requestDataInfo.setValue(name);
                                    requestDataInfo.setType("method");

                                    //异步分发任务
                                    mallAdminConfig.getJobSendHelper().send(mallAdminConfig, strategyEnum, requestDataInfo, jobDistributeInfo.getFailRetryCount());
                                } catch (Exception e) {
                                    log.error("执行任务失败！ job is {}", name);
                                    log.error(e.getMessage(), e);
                                }
                            }
                        });
                    }
                }
            }
        });

        thread.setName("JobSendHelper");
        thread.setDaemon(true);
        thread.start();
    }

    public void toStop() {

        // 1.sendStop置为true
        sendStop = true;

        if (poolExecutor != null) {
            // 2.停止线程池
            poolExecutor.shutdown();
        }
    }
}
